#include <fstream>
#include <vector>
#include <iostream>
#include <map>
#include <queue>
#include <exception>
#include <algorithm>
struct pcb
{
    int id;
    int release_time;
    int priority;
    int cpu_time;
};
int main()
{
    std::ifstream file_reader("task.txt");
    if (not file_reader)
        throw std::runtime_error("cannot open the file");
    if (file_reader.eof())
        return 0;
    std::vector<pcb> pcbs;
    pcb temp;
    file_reader >> temp.id >> temp.release_time >> temp.priority >> temp.cpu_time;
    pcbs.push_back(temp);
    for (std::vector<pcb>::iterator release_first(pcbs.begin());not file_reader.eof();)
    {
        file_reader >> temp.id >> temp.release_time >> temp.priority >> temp.cpu_time;
        if (temp.release_time == release_first->release_time)
            pcbs.insert(std::upper_bound(release_first, pcbs.end(), temp.cpu_time, [](const int temp_time, const pcb& b)
                {
                    return temp_time < b.cpu_time;
                }), temp);
        else
        {
            pcbs.push_back(temp);
            release_first = pcbs.end() - 1;
        }
    }
    int time = 0;
    for (std::vector<pcb>::iterator p(pcbs.begin());p not_eq pcbs.end();++p)
    {
        time = std::max(time, p->release_time) + p->cpu_time;
        std::map<int, std::queue<pcb>> temp;
        std::vector<pcb>::iterator q;
        for (q = p + 1;q not_eq pcbs.end() and q->release_time <= time;++q)
        {
            q->release_time = time;
            temp[q->cpu_time].push(*q);
        }
        q = p + 1;
        for (std::pair<const int, std::queue<pcb>>& bucket : temp)
            for (;not bucket.second.empty();++q)
            {
                *q = bucket.second.front();
                bucket.second.pop();
            }
    }
    std::cout << "pid\tcpu_time\n";
    for (const pcb& p : pcbs)
        std::cout << p.id << '\t' << p.cpu_time << '\n';
    system("pause");
}